#https://blog.csdn.net/qq_51865683/article/details/123295569
#https://cloud.tencent.com/developer/news/311861

#netsh WLAN show interfaces

# pip install comtypes
import time
import pywifi
from pywifi import const

class WiFi:
    """WiFi状态检查，连接，扫描"""
    def __init__(self):
        self.wifi = pywifi.PyWiFi()
        self.iface = self.wifi.interfaces()[0] #acquire the first Wlan card,maybe not

    def ConnectStatus(self):
        if self.iface.status() in [const.IFACE_CONNECTED,const.IFACE_INACTIVE]:
            #print("wifi connected!")
            return 0
        else:
            #print("wifi not connected!")
            return 1

    def Scan(self):
        self.iface.scan()
        #time.sleep(1)
        basewifi = self.iface.scan_results()
        for i in basewifi:
            print("wifi scan result:{}".format(i.ssid).encode('raw_unicode_escape').decode('utf-8'))
            print("wifi device MAC address:{}".format(i.bssid).encode('raw_unicode_escape').decode('utf-8'))
        return basewifi

    def Connect(self, ssid, password):
        #print(ifaces.name())               #输出无线网卡名称
        self.iface.disconnect()
        #time.sleep(3)

        profile = pywifi.Profile()                          #配置文件
        profile.ssid = ssid                                 #wifi名称
        profile.auth = const.AUTH_ALG_OPEN                  #需要密码
        profile.akm.append(const.AKM_TYPE_WPA2PSK)          #加密类型
        profile.cipher = const.CIPHER_TYPE_CCMP             #加密单元
        profile.key = password                              #wifi密码

        self.iface.remove_all_network_profiles()                #删除其它配置文件
        tmp_profile = self.iface.add_network_profile(profile)   #加载配置文件
        self.iface.connect(tmp_profile)
        #time.sleep(5)

        if self.iface.status() == const.IFACE_CONNECTED:
            #print("connect successfully!")
            return 0
        else:
            #print("connect failed!")
            return 1

def main():
    Wifi = WiFi()
    if Wifi.ConnectStatus():
        Wifi.Connect('Test-5G', 'Test=999')
    Wifi.Scan()

if __name__ == "__main__":
    main()